package com.shuzixiangcun.utils;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;

/**
 * @author CHFSUN
 * @date 2024-05-16 21:24
 */
@Service
public class UploadUtil {
    private Logger logger = LoggerFactory.getLogger(UploadUtil.class);

    public  String upLoadFiles(String savePath,MultipartFile file, HttpServletRequest request){
        //设置支持最大上传的文件，这里是1024*1024*2=2M
        long MAX_SIZE=3097152L;
        //获取要上传文件的名称
        String fileName=file.getOriginalFilename();
        logger.info("源文件名为："+fileName);
        //如果名称为空，返回一个文件名为空的错误
        if (StringUtils.isEmpty(fileName)){
            return "当前文件名称不能为空！";
        }
        //如果文件超过最大值，返回超出可上传最大值的错误
        logger.debug("文件大小：" + file.getSize());
        if (file.getSize()>MAX_SIZE){
            return "文件大小超出限定！";
        }
        String downloadFilePath= null;

        //String localDirString = request.getSession().getServletContext().getRealPath( File.separator+"uploads");
        //String localDirString  = "G:\\t2291s2\\s3-springboot\\my-cvs\\src\\main\\resources\\uploads\\";
        String localDirString = savePath;
        logger.info("上传文件路径"+localDirString);
        //在tomcat服务器部署的项目路径
        String root_String = request.getSession().getServletContext().getRealPath("/uploads");
        File localDirPath = new File(localDirString);
        File root_Path = new File(root_String);
        //获取到后缀名
        String suffixName = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".")+1) : null;
        logger.debug("原文件后缀为：" + suffixName);

        if(suffixName.equalsIgnoreCase("jpg") || suffixName.equalsIgnoreCase("png")
                || suffixName.equalsIgnoreCase("jpeg") || suffixName.equalsIgnoreCase("pneg")){
            //文件的保存重新按照时间戳命名
            String newName = System.currentTimeMillis() + "."+suffixName;
            logger.debug("新生成的文件名称为：" + file.getName());
            //File targetFile = new File(uploadFilePath);
            //本地IDEA中目录不存在则需要创建
            if (!localDirPath.exists()) {
                localDirPath.mkdirs();
            }
            //服务器tomcat中目录不存在则创建
            if (!root_Path.exists()) {
                root_Path.mkdirs();
            }
            // 本地的文件路径
            File localFilePath = new File(localDirPath + File.separator + newName);//文件目录+文件名称
            // 服务器中文件的路径
            File root_FilePath = new File(root_Path + File.separator + newName);//项目部署的目录+文件名称
            //保存
            try {
                //file.transferTo(new File(targetFile, newName));
                file.transferTo(localFilePath);
                //从本地路径复制一份文件到tomcat服务器的下//避免重新部署是图片资源丢失
                Files.copy(localFilePath.toPath(), root_FilePath.toPath());
            } catch (Exception e) {
                e.printStackTrace();
                ResponseEntity.status(500).header("Custom-Header", "foo")
                        .body(" * 上传失败！");
            }
            System.out.println("上传图片到本地保存的路径：" + localFilePath);
            //System.out.println("上传图片到部署项目的路径：" + root_FilePath);
            String idPicPath = File.separator+"uploads" + File.separator+newName;
            // 将文件路径的反斜杠替换为正斜杠
            String newIdPath = idPicPath.replaceAll("\\\\","/");
            downloadFilePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+newIdPath;
            logger.info("生成的url路径是："+downloadFilePath);
        }else{
            ResponseEntity.status(500).header("Custom-Header", "foo")
                    .body("* 上传图片格式不正确!");
        }
        return downloadFilePath;
    }

    /**
     * 下载
     * @param picPath
     * @return
     */
    public InputStream getFileInputStream(String picPath) {
        File file = new File(picPath);
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}
